from fastapi import FastAPI, Body
from fastapi.middleware.cors import CORSMiddleware
import subprocess

# 创建FastAPI应用实例
app = FastAPI()

# 配置CORS中间件，允许跨域请求

# 允许跨域请求
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.post("/execute")
async def execute_code(code: str = Body(..., media_type="text/plain")):
    """
    执行Python代码的API接口
    :param code: 要执行的Python代码
    :return: 执行结果，包含状态和输出
    """
    print(code)
    with open("a.txt","r",encoding="utf-8") as f:
        inputStrings = f.read().split("####\n")
    with open("r.txt","r",encoding="utf-8") as f:
        resultStrings = f.read().split("####\n")
    print(inputStrings)
    print(resultStrings)
    try:
        # 使用subprocess执行Python代码
        errortype=0
        for i in range(len(inputStrings)):
            result = subprocess.run(
                ["python", "-c", code],  # 通过命令行执行Python代码
                input=inputStrings[i],
                stdout=subprocess.PIPE,     # 捕获输出
                stderr=subprocess.PIPE,
                #capture_output=True,    # 捕获标准输出和错误输出
                text=True,              # 以文本形式返回输出
                timeout=5               # 设置5秒超时
            )
            # 根据返回码判断执行结果
            if result.returncode != 0:
                errortype = 1
                break
            else:
                print(f"===result.stdout:{result.stdout}========")
                print(f"===resultString:{resultStrings[i]}=======")
                if result.stdout!=resultStrings[i]:
                    errortype = 2
                    break
        if errortype==0:
            return {"status": "success", "output": "执行通过"}  # 执行成功
        elif errortype == 1:
            return {"status": "error", "output": result.stderr}    # 执行失败
        else:
            return {"status": "error", "output": f"程序可以正常运行，但结果不正确\n\n\n输入：\n{inputStrings[i]}\n\n\n期望输出：{resultStrings[i]}\n实际输出：{result.stdout}"}    # 执行失败
    except subprocess.TimeoutExpired:
        return {"status": "error", "output": "Execution timed out"}  # 超时错误
    except Exception as e:
        return {"status": "error", "output": str(e)}  # 其他异常

if __name__ == "__main__":
    # 使用uvicorn运行FastAPI应用
    import uvicorn
    uvicorn.run(app, host="::", port=8000)  # 监听所有IP（IPv4和IPv6），端口8000
